import {
  HYEventStore
} from 'hy-event-store'

import {
  getReqSongDetail,
  getReqSongLyric
} from '../service/player'

import {
  parseLyric
} from '../utils/parse-lyric'

export const audioContext = wx.createInnerAudioContext()

export const playStore = new HYEventStore({
  state: {
    playSongs: [],
    songIndex: 0,

    id: 0,
    currSong: {},
    lyricInfo: '',
    currTime: 0,
    durationTime: 0,
    isPlay: true,
    lyricInfos: [],
    currentLyricIndex: 0,
    playSongs: [],
    songIndex: 0,
    playModeIndex: 0, // 0:顺序播放 1:单曲播放 2.循环播放
    isFirstPlay: true,
    isPlay: true
  },
  actions: {
    changePlayMusicWithId(state, id) {
      state.currSong = {}
      state.currTime = 0
      state.durationTime = 0

      state.id = id
      // 获取歌曲详情
      getReqSongDetail(id).then(res => {
        state.currSong = res.songs[0]
        state.durationTime = res.songs[0].dt
      })
      // 获取歌词
      getReqSongLyric(id).then(res => {
        const lyricInfos = parseLyric(res.lrc.lyric)
        state.lyricInfos = lyricInfos
      })
      // 歌曲播放
      audioContext.stop()
      audioContext.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
      audioContext.autoplay = true

      if (state.isFirstPlay) {
        state.isFirstPlay = false
        // 当音频因为数据不足，需要停下来加载时会触发
        audioContext.onWaiting(() => {
            // 暂停
            audioContext.pause()
          }),

          // 监听音频播放事件
          audioContext.onCanplay(() => {
            // 暂停情况下 点击滑块不播放
            if (!state.isPlay) {
              audioContext.pause()
            } else {
              // 播放
              audioContext.play()
            }
          })

        audioContext.onTimeUpdate(() => {
          // 获取当前播放的时间
          state.currTime = audioContext.currentTime * 1000

          // if (!this.data.isSlider) {
          //   throttleUpdateTime()
          // }
          //  获取歌词
          if (!state.lyricInfos.length) return
          //  根据播放时间获取歌词的索引  且防止最后一句歌词拿不到
          let index = state.lyricInfos.length - 1
          for (let i = 0; i < state.lyricInfos.length; i++) {
            if (audioContext.currentTime * 1000 < state.lyricInfos[i].time) {
              index = i - 1
              break
            }
          }
          if (state.currentLyricIndex === index) return
          const lyricInfo = state.lyricInfos[index].text
          state.lyricInfo = lyricInfo
          state.currentLyricIndex = index
        })
        // 监听音频播放到自然结束
        audioContext.onEnded(() => {
          // 如果是单曲循环  不需要切换到下一首歌
          if (audioContext.loop) return

          // 切换到下一首歌
          // this.changeNewSongs()
          // todo: 切换到下一首歌
        })
      }
    },
    changePlayMusicWithIdAction(state) {
      if (!audioContext.paused) {
        state.isPlay = false
        audioContext.pause()
      } else {
        state.isPlay = true
        audioContext.play()
      }
    },
    changePlayModeIndex(state) {
      let modeIndex = state.playModeIndex
      modeIndex = modeIndex + 1
      if (modeIndex === 3) modeIndex = 0

      if (modeIndex === 1) {
        audioContext.loop = true
      } else {
        audioContext.loop = false
      }

      state.playModeIndex = modeIndex
    },
    changePlayNewSong(state, isNext = true) {
      // 获取当前歌曲的信息
      let index = state.songIndex
      const length = state.playSongs.length
      switch (state.playModeIndex) {
        case 0: //顺序播放
          // 判断是否是点击下一首
          index = isNext === true ? index + 1 : index - 1
          if (index === length) index = 0
          if (index === -1) index = length - 1
          break
        case 1: //循环播放
          break
        case 2: //随机播放
          // 取值范围： 0 - length - 1
          index = Math.floor(Math.random() * length)
          break
      }

      // 获取数据
      const currSong = state.playSongs[index]
      state.songIndex = index
      this.dispatch('changePlayMusicWithId', currSong.id)
    }
  }
})